<template>
  <!-- 租赁分析 -->
  <div class="lease-analysis chart-box2">
    <div class="chart-title">租赁分析</div>
    <div class="chart-content">
      <div class="chart-container" :id="chartId"></div>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  onBeforeUnmount,
  nextTick,
  watch,
  toRaw,
} from "vue";
import { Chart, registerTheme } from "@antv/g2";
import DataSet from "@antv/data-set";
import common from "../../utils/common";
import store from "../../../../store";

export default defineComponent({
  name: "LeaseAnalysis",
  components: {},
  setup() {
    const state = reactive({
      chartId: "leaseAnalysisChart",
      chart: null,
      data: {
        nodes: [],
        links: [],
      },
    });

    const initChart = () => {
      /**
       const DATA = {
        nodes: [
          {
            name: "腾讯科技",
          },
          {
            name: "阿里巴巴",
          },
          {
            name: "网易",
          },
          {
            name: "字节跳动",
          },
          {
            name: "拼多多",
          },
          {
            name: "",
          },
          {
            name: "计算机",
          },
          {
            name: "餐饮",
          },
          {
            name: "服务",
          },
          {
            name: "土木",
          },
          {
            name: "生物制药",
          },
        ],
        links: [
          {
            source: 0,
            target: 5,
            value: 600,
          },
          {
            source: 1,
            target: 5,
            value: 400,
          },
          {
            source: 2,
            target: 5,
            value: 100,
          },
          {
            source: 3,
            target: 5,
            value: 80,
          },
          {
            source: 4,
            target: 5,
            value: 80,
          },
          {
            source: 5,
            target: 6,
            value: 400,
          },
          {
            source: 5,
            target: 7,
            value: 300,
          },
          {
            source: 5,
            target: 8,
            value: 240,
          },
          {
            source: 5,
            target: 9,
            value: 135,
          },
          {
            source: 5,
            target: 10,
            value: 125,
          },
        ],
      };
       */

      const DATA = state.data;

      // arc diagram layout
      const ds = new DataSet();
      const dv = ds.createView().source(DATA, {
        type: "graph",
        edges: (d) => d.links,
      });
      dv.transform({
        type: "diagram.sankey",
        nodeWidth: 0.008,
        nodePadding: 0.03,
        sort: (a, b) => {
          if (a.value > b.value) {
            return 0;
          } else if (a.value < b.value) {
            return -1;
          }
          return 0;
        },
      });

      const edges = dv.edges.map((edge) => {
        return {
          source: edge.source.name,
          target: edge.target.name,
          // name: edge.target.name,
          name: edge.source.name || edge.target.name,
          x: edge.x,
          y: edge.y,
          value: edge.value,
        };
      });

      const nodes = dv.nodes.map((node) => {
        return {
          x: node.x,
          y: node.y,
          name: node.name,
        };
      });

      // ============= 绘图
      state.chart = new Chart({
        container: state.chartId,
        autoFit: true,
        appendPadding: 16,
        // syncViewPadding: true,
      });

      state.chart.legend(false);

      state.chart.tooltip({
        showTitle: false,
        showMarkers: false,
      });

      state.chart.axis(false);

      state.chart.scale({
        x: { sync: true, nice: true },
        y: { sync: true, nice: true },
        source: { sync: "color" },
        name: { sync: "color" },
      });

      // node view
      const nodeView = state.chart.createView();
      nodeView.data(nodes);
      nodeView
        .polygon()
        .position("x*y") // nodes数据的x、y由layout方法计算得出
        .color("name")
        .label("x*name", (x, name) => {
          const isLast = x[1] === 1;
          return {
            style: {
              fill: "rgba(255,255,255,0.6)",
              textAlign: isLast ? "end" : "start",
            },
            offsetX: isLast ? -8 : 8,
            content: name,
          };
        })
        .tooltip(false);
      // .style("name", (name) => {
      //   if (!name === "租赁") {
      //     return {
      //       fill: "#5D7092",
      //       stroke: "#5D7092",
      //     };
      //   }
      //   return {};
      // });

      // edge view
      const edgeView = state.chart.createView();
      edgeView.data(edges);

      console.log(edges);
      edgeView
        .edge()
        .position("x*y")
        .shape("arc")
        .color("name")
        .tooltip("target*source*value", (target, source, value) => {
          return {
            // name: source + " to " + target,
            name: target || source,
            value: value + "%",
          };
        })
        .style("source*target", (source, target) => {
          return {
            opacity: 0.6,
            lineWidth: 0,
          };
        })
        .state({
          active: {
            style: {
              // opacity: 0.8,
              lineWidth: 0,
            },
          },
        });

      state.chart.interaction("element-active");

      state.chart.render();
    };

    watch(
      () => store.getters.rentControl.LeaseAnalysis,
      (val) => {
        if (val) {
          getData();
        }
      }
    );

    const getData = () => {
      const { LeaseAnalysis } = store.getters.rentControl;
      if (LeaseAnalysis) {
        console.log("---------LeaseAnalysis", toRaw(LeaseAnalysis));
        const { industryRankList, leaseRankList } = LeaseAnalysis;
        const nodes = [];
        industryRankList.forEach((item) => {
          nodes.push({
            name: item.industry_name,
          });
        });
        nodes.push({ name: "" });
        leaseRankList.forEach((item) => {
          nodes.push({
            name: item.owner_name,
          });
        });
        const links = [];
        for (
          let i = 0;
          i <= industryRankList.length + leaseRankList.length;
          i++
        ) {
          if (i != industryRankList.length) {
            links.push({
              source: i < industryRankList.length ? i : industryRankList.length,
              target: i < industryRankList.length ? industryRankList.length : i,
              value:
                i < industryRankList.length
                  ? Number(industryRankList[i].percent)
                  : Number(
                      leaseRankList[i - industryRankList.length - 1].percent
                    ),
            });
          }
        }
        state.data = {
          nodes,
          links,
        };
        console.log("---------LeaseAnalysis => state.data", toRaw(state.data));
        if (state.chart) {
          state.chart.changeData(toRaw(state.data));
        } else {
          nextTick(() => {
            initChart();
          });
        }
      }
    };
    onMounted(() => {
      registerTheme("chartTheme", common.chartTheme);
      getData();
    });

    onBeforeUnmount(() => {
      const chartBox = document.getElementById(state.chartId);
      if (chartBox) {
        chartBox.innerHTML = "";
      }
    });
    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
@import "../../styles/common.less";
</style>
